package com.server.modules.sys.utils.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * Created by Administrator on 2017/1/10.
 */
public class EmailUtils {
    private static String fromMail = "info@chxbc.com";
    private static String fromMailPwd = "Xb2016";
    private static String host = "smtp.exmail.qq.com";
    private static Session mailSession = null;
    static {
        // 配置发送邮件的环境属性
        final Properties props = new Properties();
        /*
         * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
         * mail.user / mail.from
         */
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", host);
        // 发件人的账号
        props.put("mail.user", fromMail);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", fromMailPwd);
        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        mailSession = Session.getInstance(props, authenticator);
        //调试模式
        mailSession.setDebug(true);
    }

    public static void sendTextMail(){

    }

    /**
     * 发送邮件
     * @param fromNickName 发件人昵称
     * @param fromMail 发件人
     * @param toMail 收件人
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @param mimeType 邮件内容类型：内容类型 默认为"text/plain;charset=UTF-8",如果要发送HTML内容,应设置为"text/html;charset=UTF-8"
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    private static void sendMail(String fromNickName, String fromMail, String toNickName, String toMail, String subject, String mailContent, String mimeType) throws UnsupportedEncodingException, MessagingException {
        // 创建邮件消息
        MimeMessage mimeMessage = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress formAddress = new InternetAddress(fromMail);
        if(fromNickName!=null && fromNickName!=""){
            formAddress.setPersonal(fromNickName, "UTF-8"); // 发件人昵称（UTF-8编码）
        }
        mimeMessage.setFrom(formAddress);

        // 设置收件人
        InternetAddress toAddress = new InternetAddress(toMail);
        if(toNickName!=null && toNickName!=""){
            toAddress.setPersonal(toNickName, "UTF-8"); // 收件人昵称（UTF-8编码）
        }
        mimeMessage.setRecipient(Message.RecipientType.TO, toAddress); //收件人邮件

        // 设置邮件标题
        mimeMessage.setSubject(subject==null ? "" : subject);

        // 设置邮件的内容体
        if(mimeType==null || mimeType=="")
            mimeType = "text/plain;charset=UTF-8";
        mimeMessage.setContent(mailContent==null ? "" : mailContent, mimeType);

        // 发送邮件
        Transport.send(mimeMessage);
    }

    /**
     * 发送邮件,可以发送多人，和抄送密送多人
     * @param fromNickName 发件人昵称，为null则默认使用邮箱名
     * @param fromMail 发件人，必须
     * @param toMails 收件人，必须
     * @param carbonCopyMails 抄送，为null没有抄送人
     * @param blindCarbonCopyMails 密送，为null没有密送人
     * @param subject 邮件主题，必须
     * @param mailContent 邮件内容，必须
     * @param mimeType 邮件内容类型：内容类型 默认为"text/plain;charset=UTF-8",如果要发送HTML内容,应设置为"text/html;charset=UTF-8"
     * @param attachements 附件
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    private static void sendMail(String fromNickName, String fromMail, String[] toMails, String[] carbonCopyMails, String[] blindCarbonCopyMails, String subject, String mailContent, String mimeType, File[] attachements) throws UnsupportedEncodingException, MessagingException {
        // 创建邮件消息
        MimeMessage mimeMessage = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress formAddress = new InternetAddress(fromMail);
        if(fromNickName!=null && fromNickName!=""){
            formAddress.setPersonal(fromNickName, "UTF-8"); // 昵称（UTF-8编码）
        }
        mimeMessage.setFrom(formAddress);

        // 设置收件人
        if(toMails!=null && toMails.length>0) {
            InternetAddress[] toAddress = new InternetAddress[toMails.length];
            for (int i = toMails.length - 1; i >= 0; i--) {
                toAddress[i] = new InternetAddress(toMails[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
        }

        // 设置抄送
        if(carbonCopyMails!=null && carbonCopyMails.length>0){
            InternetAddress[] ccAddress = new InternetAddress[carbonCopyMails.length];
            for (int i = carbonCopyMails.length-1; i>=0; i--) {
                ccAddress[i] = new InternetAddress(carbonCopyMails[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.CC, ccAddress);
        }

        // 设置密送，其他的收件人不能看到密送的邮件地址
        if(blindCarbonCopyMails!=null && blindCarbonCopyMails.length>0) {
            InternetAddress[] bccAddress = new InternetAddress[blindCarbonCopyMails.length];
            for (int i = blindCarbonCopyMails.length-1; i>=0; i--) {
                bccAddress[i] = new InternetAddress(blindCarbonCopyMails[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddress);
        }

        // 设置邮件标题
        mimeMessage.setSubject(subject==null ? "" : subject);

        //邮件内容
        Multipart multipart = new MimeMultipart();

        // 正文
        MimeBodyPart body = new MimeBodyPart();
        // 设置邮件的内容体
        if(mimeType==null || mimeType=="")
            mimeType = "text/plain;charset=UTF-8";
        body.setContent(mailContent==null ? "" : mailContent, mimeType);
        multipart.addBodyPart(body);// 发件内容

        // 附件
        if (attachements != null) {
            for (File attachement : attachements) {
                if(attachement==null) continue;

                MimeBodyPart attache = new MimeBodyPart();
                attache.setDataHandler(new DataHandler(new FileDataSource(attachement)));
                String fileName = getLastName(attachement.getName());
                attache.setFileName(MimeUtility.encodeText(fileName, "UTF-8", null));
                multipart.addBodyPart(attache);
            }
        }
        mimeMessage.setContent(multipart);
        mimeMessage.setSentDate(new Date());

        // 发送邮件
        Transport.send(mimeMessage);
    }

    /**获取文件名*/
    private static String getLastName(String fileName) {
        if(fileName==null || fileName=="")
            return fileName;
        int pos = fileName.lastIndexOf("\\");
        if (pos > -1) {
            fileName = fileName.substring(pos + 1);
        }
        pos = fileName.lastIndexOf("/");
        if (pos > -1) {
            fileName = fileName.substring(pos + 1);
        }
        return fileName;
    }

    /**
     *  发送html格式的邮件
     * @param toMail 收件人
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendHtmlMail(String toMail, String subject, String mailContent) throws UnsupportedEncodingException, MessagingException {
//        String nickName = "";
//        String fromMail = "";
        sendMail(null, fromMail, null, toMail, subject, mailContent, "text/html;charset=UTF-8");
    }

    /**
     * 发送html格式邮件，可以发送多人，也可以抄送和密送
     * @param toMails 收件人
     * @param carbonCopyMails 抄送
     * @param blindCarbonCopyMails 密送
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendHtmlMail(String[] toMails, String[] carbonCopyMails, String[] blindCarbonCopyMails, String subject, String mailContent) throws UnsupportedEncodingException, MessagingException {
//        String nickName = "";
//        String fromMail = "";
        sendMail(null, fromMail, toMails, carbonCopyMails, blindCarbonCopyMails, subject, mailContent, "text/html;charset=UTF-8", null);
    }

    /**
     * 发送html格式邮件，可以发送多人，也可以抄送和密送，可以带附件
     * @param toMails 收件人
     * @param carbonCopyMails 抄送
     * @param blindCarbonCopyMails 密送
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @param attachements 附件
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendHtmlMail(String[] toMails, String[] carbonCopyMails, String[] blindCarbonCopyMails, String subject, String mailContent, File[] attachements) throws UnsupportedEncodingException, MessagingException {
//        String nickName = "";
//        String fromMail = "";
        sendMail(null, fromMail, toMails, carbonCopyMails, blindCarbonCopyMails, subject, mailContent, "text/html;charset=UTF-8", attachements);
    }

    /**
     *  发送Text格式的邮件
     * @param toMail 收件人
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendTextMail(String toMail, String subject, String mailContent) throws UnsupportedEncodingException, MessagingException {
//        String nickName = "";
//        String fromMail = "";
        sendMail(null, fromMail, null, toMail, subject, mailContent, "text/plain;charset=UTF-8");
    }

    /**
     * 发送Text格式的邮件，可以发送多人，也可以抄送和密送
     * @param toMails 收件人
     * @param carbonCopyMails 抄送
     * @param blindCarbonCopyMails 密送
     * @param subject 邮件主题
     * @param mailContent 邮件内容
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static void sendTextMail(String[] toMails, String[] carbonCopyMails, String[] blindCarbonCopyMails, String subject, String mailContent) throws UnsupportedEncodingException, MessagingException {
//        String nickName = "";
//        String fromMail = "";
        sendMail(null, fromMail, toMails, carbonCopyMails, blindCarbonCopyMails, subject, mailContent, "text/plain;charset=UTF-8", null);
    }

    public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
        //测试发送简单邮件
        EmailUtils.sendTextMail("314667996@qq.com", "测试发送邮件", "<a href='http://www.fkjava.org'>测试的HTML邮件</a>");
    //    SendEMailUtil.sendHtmlMail("abc2@abc.com", "测试发送邮件", "<a href='http://www.fkjava.org'>测试的HTML邮件</a>");
//        SendEMailUtil.sendHtmlMail("abc2@abc.com", "测试发送邮件", null);
//        SendEMailUtil.sendHtmlMail("abc2@abc.com", null, null);
//        SendEMailUtil.sendHtmlMail(null, null, null);

//        String[] toMails = {"abc2@abc.com"};
//        String[] carbonCopyMails = {"abc3@abc.com"};
//        String[] blindCarbonCopyMails = {"abc4@abc.com"};
//        File[] attachements = new File[]{
//                new File("C:\\Users\\jack\\Desktop\\idea 快捷键02.png"),
//                new File("C:\\Users\\jack\\Desktop\\idea快捷键.jpg"),
//                new File("C:/Users/jack/Desktop/idea快捷键.jpg")
//        };
//        SendEMailUtil.sendTextMail(toMails, carbonCopyMails, blindCarbonCopyMails, "测试发送邮件1", "<a href='http://www.fkjava.org'>测试的HTML邮件</a>");
//        SendEMailUtil.sendHtmlMail(toMails, carbonCopyMails, blindCarbonCopyMails, "测试发送邮件1", "<a href='http://www.fkjava.org'>测试的HTML邮件</a>");
//        SendEMailUtil.sendHtmlMail(toMails, carbonCopyMails, blindCarbonCopyMails, null, null);
//        SendEMailUtil.sendHtmlMail(toMails, null, null, null, null);
//        SendEMailUtil.sendHtmlMail(toMails, carbonCopyMails, blindCarbonCopyMails, "测试发送邮件1", "<a href='http://www.fkjava.org'>测试的HTML邮件</a>", attachements);
    }


}
